package com.shujia.mr.stu;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Demo03StuJoin {
    // 关联学生信息数据及总分：id、name、age、gender、clazz、sumScore

    // Mapper
    public static class MyMapper extends Mapper<LongWritable, Text, IntWritable, Text> {
        @Override
        // 学生数据：1500100001,施笑槐,22,女,文科六班
        // 总分数据：1500100001	406
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, IntWritable, Text>.Context context) throws IOException, InterruptedException {
            // 通过分隔符判断是哪类数据
            String line = value.toString();
            // 学生数据
            if (line.contains(",")) {
                String[] splits = line.split(",");
                if (splits.length == 5) {
                    String id = splits[0];
                    String name = splits[1];
                    String age = splits[2];
                    String gender = splits[3];
                    String clazz = splits[4];
                    context.write(new IntWritable(Integer.parseInt(id)), new Text("$" + name + "," + age + "," + gender + "," + clazz));
                }
            } else {
                // 总分数据
                String[] splits = line.split("\t");
                if (splits.length == 2) {
                    String id = splits[0];
                    String sumScore = splits[1];
                    context.write(new IntWritable(Integer.parseInt(id)), new Text("#" + sumScore));
                }
            }
        }
    }

    // Reducer
    public static class StuJoin extends Reducer<IntWritable, Text, Text, NullWritable> {
        @Override
        protected void reduce(IntWritable key, Iterable<Text> values, Reducer<IntWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {
            // 1500100001 ["$施笑槐,22,女,文科六班","#406"]
//            context.write(
//                    new Text(key + "," + StringUtils
//                            .join(values.iterator(), "|")
//                            .replace("$", "")
//                            .replace("#", ""))
//                    , NullWritable.get()
//            );

            // 保证总分在最后
            String stu = "";
            String sumScore = "";
            for (Text value : values) {
                String str = value.toString();
                if (str.contains("$")) {
                    stu = str.replace("$", "");
                } else {
                    sumScore = str.replace("#", "");
                }
            }

            context.write(new Text(key + ":" + stu + "|" + sumScore), NullWritable.get());

        }
    }

    // Driver
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);

        // 配置Job
        job.setJobName("Demo03StuJoin");
        job.setJarByClass(Demo03StuJoin.class);

        // 配置Mapper
        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(IntWritable.class);
        job.setMapOutputValueClass(Text.class);

        // 配置Reducer
        job.setReducerClass(StuJoin.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(NullWritable.class);

        // 验证args的长度
        if (args.length != 3) {
            System.out.println("请传入输入输出目录！");
            return;
        }

        String input01 = args[0];
        String input02 = args[1];
        String output = args[2];

        // 配置输入输出的路径
        // 学生信息数据
        FileInputFormat.addInputPath(job, new Path(input01));
        // 学生总分数据
        FileInputFormat.addInputPath(job, new Path(input02));

        Path ouputPath = new Path(output);
        // 通过FileSystem来实现覆盖写入
        FileSystem fs = FileSystem.get(conf);
        if (fs.exists(ouputPath)) {
            fs.delete(ouputPath, true);
        }
        // 该目录不能存在，会自动创建，如果已存在则会直接报错
        FileOutputFormat.setOutputPath(job, ouputPath);

        // 启动任务
        // 等待任务的完成
        job.waitForCompletion(true);

    }
}
